package com.suixun.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.authority.common.MD5Util;
import com.authority.common.UserTypeEnum;
import com.authority.controller.BaseManager;
import com.google.gson.Gson;
import com.suixun.Result;
import com.suixun.entity.form.ParentForm;
import com.suixun.enums.APICode;
import com.suixun.queue.SMSDeal;
import com.suixun.service.impl.ParentServiceImpl;
import com.suixun.util.Constant;
import com.suixun.util.StringUtil;
/**
 * 
 * <p>Title: ParentController</p>
 * <p> 功能描述:家长信息管理服务 </p> 
 * @author	陈显强
 * @date	2016年12月12日上午8:39:34
 * @version 1.0
 */
@Controller
@RequestMapping("/parentInfoManage")
public class ParentController extends BaseManager{
	@Resource
	private ParentServiceImpl parentService;
	@Resource
	private SMSDeal sMSDeal;

	/**
	 * 
	 * <p>Title: queryParentList</p>
	 * <p> 功能描述:查询家长信息列表 </p>
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryParentList.json")
	public Object queryParentList(String param){
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		try {
			ParentForm parent=new Gson().fromJson(param,ParentForm.class);
			if (getUserType(getUserId()) == UserTypeEnum.REGIONMAN.getType()) {
				parent.setUserid(getUserId());
			}
			return success(parentService.queryList(parent));
		} catch (Exception e) {
			logger("ParentController queryParentList:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 
	 * <p>Title: queryParents</p>
	 * <p> 功能描述:查询对应的家长信息 </p>
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/queryParents.json")
	public Object queryParents(String param){
		if (param == null) {
			return fail(Constant.EMPTY);
		}
		try {
			ParentForm parent=new Gson().fromJson(param,ParentForm.class);
			boolean isParam = StringUtil.isEmpty(parent.getMdtid()) && StringUtil.isEmpty(parent.getSimid());
			if(parent==null || isParam){
				return fail(Constant.EMPTY); 
			}
			return success(parentService.queryParents(parent));
		} catch (Exception e) {
			logger("ParentController queryParents:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	/**
	 * 
	 * <p>Title: updateTel</p>
	 * <p> 功能描述:修改家长手机号 </p>
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/phoneService.json")
	public Object updateParentTel(String param){
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if(param==null){
			return fail(Constant.EMPTY);
		}
		try {
			ParentForm parent=new Gson().fromJson(param,ParentForm.class);
			if(!StringUtil.isNotEmpty(parent.getParentphone())){
				return fail(Constant.EMPTY);
			}
			/*if(parentService.telIsExsit(parent.getParentphone())!=null){
				return fail(Constant.People.PEOPLE_TEL_EXIST);
			}*/
			parent.setOperationerid(getUserId().toString());
			parent.setOperationerName(getUsername());
			parent.setParentoldphone(parentService.queryOldTel(parent.getParentid()));
			//修改手机号
			String isUpdate=parentService.updateParentTel(parent);
			HashMap<String ,String> result=new HashMap<String ,String>();
			if(isUpdate == null){
				//将短信内容放到队列里去
				Map<String,String> arr = new HashMap<>();
				arr.put("module", "updateTel");
				arr.put("telephone", parent.getParentphone());
				sMSDeal.send(arr);
				result.put("resultstatus", "1");
				result.put("resultinfo", Constant.OPERATE_SUCCESS);
				return success(result);
			}else{
				return fail(isUpdate);
			}
		}catch (Exception e) {
			logger("ParentController updateParentTel:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	/**
	 * 
	 * <p>Title: resetParentPassword</p>
	 * <p> 功能描述:重置密码 </p>
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/passwordService.json")
	public Object resetParentPassword(String param){
		boolean bln=checkRight();
		if(!bln) {
			return fail(Constant.Authority.CHECK_FALSE);
		}
		if(param==null){
			return fail(Constant.EMPTY);
		}
		try {
			ParentForm parent=new Gson().fromJson(param,ParentForm.class);
			if(!StringUtil.isNotEmpty(parent.getMdtid())){
				return fail(Constant.EMPTY);
			}
			//int randomPassword=(int)(Math.random()*1000000);
			String randomPassword="123456";
			String encPassword=MD5Util.MD5(randomPassword);
			parent.setPassword(encPassword.toLowerCase());
			int isUpdate=parentService.updateParentPassword(parent);
			HashMap<String ,Object> result=new HashMap<String ,Object>();
			if(isUpdate==1){
				//将短信内容放到队列里去
				Map<String,String> arr = new HashMap<>();
				arr.put("module", "resetPassword");
				arr.put("telephone", parent.getParentphone());
				arr.put("password", String.valueOf(randomPassword));
				sMSDeal.send(arr);
				result.put("resultstatus", "1");
				result.put("resultinfo", Constant.OPERATE_SUCCESS);
				result.put("resultpassword", randomPassword);
				return success(result);
			}else{
				return fail(Constant.OPERATE_FAIL);
			}
		}catch (Exception e) {
			logger("ParentController resetParentPassword:"+e.getMessage(),e);
			return fail(Constant.EXCEPTION.OPERATE_FAIL);
		}
	}
	
	/**
	 * 导出批量纠正家长手机号Excel表
	 * @return
	 */
	@RequestMapping(value = "/exportbatchcorrectparenttelTemplate.json")
	@ResponseBody
	public Object exportbatchcorrectparenttelTemplate() {
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook=null;
			String[] labels = {"学生姓名","原家长手机号","家长正确手机号"};
			for (String label : labels) {
				listParm.add(label);
			}
			List<List<String>> listValue = new LinkedList<List<String>>();
			// 创建新的Excel 工作簿
			workbook = exportDeviceList("批量纠正学生家长手机号", listParm,listExample, listValue);
			HttpServletResponse response = this.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=exportbatchcorrectparenttelTemplate.xls");
			workbook.write(this.getResponse().getOutputStream());
		} catch (Exception e) {
			logger("TeacherController exportbatchcorrectparenttelTemplate:"+e.getMessage(),e);
			toRedirect(500);
		}
		return success();
	}
	
	/**
	 * 
	 * 批量纠正学生家长手机号
	 * @return
	 */
	@RequestMapping(value = "/correctPeopleTelBatch.json", method = RequestMethod.POST)
	@ResponseBody
	public Object correctPeopleTelBatch(@RequestParam("file") MultipartFile file,HttpServletRequest request){
//		boolean bln=checkRight();
//		if(!bln) {
//			return fail(Constant.Authority.CHECK_FALSE);
//		}
		InputStream fileReport = null;
		try {
			fileReport=file.getInputStream();
			String fileName = file.getOriginalFilename();
			//1.Excel是否都不为空或者有效数据
			if (fileName.endsWith("xlsx")) {
//				return fail(Constant.Excel.TYPE_IS_FALSE);
				return new Result(APICode.FAIL.setCustomMsg(Constant.Excel.TYPE_IS_FALSE), null);
			}
			//把一张xls的数据表读到wb里
			HSSFWorkbook wb = new HSSFWorkbook(fileReport);
			//批量修改手机
			
//			Object result  =changePeopleTel(wb);
			Object result  = parentService.correctPeopleTelBatch(wb);
		    return result;
			
			/*Object isImport=peopleService.importTeachers(wb);
			if (isImport instanceof String) {
				String res = (String)isImport;
				if (Constant.SUCCESS.equals(res)) {
					return success();
				}else{
					return fail(res);
				}
			}else {
				return success(isImport);
			}*/
		} catch (Exception e) {
			e.printStackTrace();
			logger("TeacherController addTeachers:"+e.getMessage(),e);
//			return fail(Constant.EXCEPTION.OPERATE_FAIL);
			return new Result(APICode.FAIL.setCustomMsg(Constant.EXCEPTION.OPERATE_FAIL), null);
		}finally{
			try {
				fileReport.close();
			} catch (IOException e) {
				logger("TeacherController addTeachers:"+e.getMessage(),e);
			}
		}
	}
	
	
	
}
